import { NMention } from "naive-ui";
import { getSlotsDom } from "../utils";
import type { BaseComponentType, OmitHTMLAttributes } from "../types";
import type { MentionProps, MentionInst } from "naive-ui";

export type MentionFactoryConstructorType = {
  props?: MentionProps;
  attrs?: OmitHTMLAttributes<"onSelect">;
  emptySlot?: BaseComponentType;
};
export class MentionFactory {
  private attrs: OmitHTMLAttributes<"onSelect"> = {};
  private props: MentionProps = {};
  private emptySlot: BaseComponentType = null;
  private domRef: MentionInst | null = null;

  constructor(data?: MentionFactoryConstructorType) {
    if (data?.props) this.setProps(data.props);
    if (data?.attrs) this.setAttrs(data.attrs);
    if (data?.emptySlot) this.setEmpty(data.emptySlot);
  }

  setAttrs(attrs: OmitHTMLAttributes<"onSelect">) {
    this.attrs = attrs;
  }
  setProps(props: MentionProps) {
    this.props = props;
  }
  setEmpty(component: BaseComponentType) {
    this.emptySlot = component;
  }

  focus() {
    this.domRef?.focus();
  }

  blur() {
    this.domRef?.blur();
  }

  create() {
    return (
      <NMention
        ref={(el: HTMLElement) => {
          this.domRef = el as unknown as MentionInst;
        }}
        {...this.attrs}
        {...this.props}
      >
        {{
          empty: () => getSlotsDom(this.emptySlot),
        }}
      </NMention>
    );
  }
}
